//
//  IMNewCarModel.m
//  BleTestDemo
//
//  Created by cjg on 2019/9/3.
//  Copyright © 2019 cjg. All rights reserved.
//

#import "IMNewCarModel.h"
#import "IMTCANManager.h"
#import "IM_FileModel.h"
#import "IM_FileGroupModel.h"

// CRC32
static const uint32_t CRC32_TABLE[256] = {
    0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};

NSString * const StandardErrorCodeDomain = @"StandardErrorCodeDomain";

@implementation IMNewCarModel

#pragma mark -- 通道一
// 安全连接读取
- (void)getSafeChannelWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelConnect property:CarConnectChannelSafe dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
           if (!error && responseData.length) {
               self.randomCode = [IMFunction AES128DecryptECB:responseData];
               NSLog(@"%@ ==安全连接== %@",responseData,self.randomCode);
           }
           compleBlock(error,responseData);
       }];
}

// 安全连接写入
- (void)setSafePasswordWithPassword:(NSData *)password successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail  {
    NSData *param = [IMFunction AES128EncryptECB:password];
    [self sendMessageWithChannel:CarChannelConnect property:CarConnectChannelSafe dataParam:param isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        NSLog(@" %@==安全连接== %@",error,responseData);
        if (!error && responseData.length) {
            uint8_t result ;
            [responseData getBytes:&result range:NSMakeRange(0, 1)];
            if (result == 1) {
                success();
            }else {
                fail(error);
            }
        }else {
            fail(error);
        }
    }];
}

#pragma mark -- 通道二
// 获取产品型号及特征
- (void)getProductMessageCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelType dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            [self analyzeProductMessageWithData:responseData];
        }
        compleBlock(error,responseData);
    }];
}

// 解析产品型号及特征信息
- (void)analyzeProductMessageWithData:(NSData *)data {
    if (!data.length) {
        return;
    }
    
    // 产品型号
    
    // 主系列
    uint8_t mainSeries ;
    [data getBytes:&mainSeries range:NSMakeRange(0, 1)];
    self.mainSeries = mainSeries;
    // 子系列
    uint8_t subSeries ;
    [data getBytes:&subSeries range:NSMakeRange(1, 1)];
    self.subSeries = subSeries;
    // 具体型号
    uint8_t deviceType ;
    [data getBytes:&deviceType range:NSMakeRange(2, 1)];
    self.deviceType = deviceType;
    // 产品批次
    uint8_t carBatch ;
    [data getBytes:&carBatch range:NSMakeRange(3, 1)];
    self.carBatch = carBatch;
    // 接口特征
    uint8_t portFeature ;
    [data getBytes:&portFeature range:NSMakeRange(4, 1)];
    self.portFeature = portFeature == 0 ? 1 : portFeature;
    // 预留特征
    uint8_t carTypeReserved ;
    [data getBytes:&carTypeReserved range:NSMakeRange(5, 1)];
    self.carTypeReserved = carTypeReserved;

    // 最终车型  030501010100
    self.LX_CarType = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x",self.mainSeries,self.subSeries,self.deviceType,self.carBatch,self.portFeature,self.carTypeReserved];
}

// 写入产品型号和批次特征
- (void)setProductMessageWithCarType:(uint16_t)carType batch:(uint16_t)batch successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    Byte byte[4] = {0};
    byte[0] = (carType & 0xff00) >> 8;
    byte[1] = carType & 0xff;
    byte[2] = (batch & 0xff00) >> 8;
    byte[3] = batch & 0xff;
    NSData *param = [NSData dataWithBytes:&byte length:4];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelType dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取车身sn
- (void)getCarSNWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelCarSN dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            self.lx_sn = [IMFunction convertDataToHexStr:responseData];
            if (self.lx_sn.length == 0) { // 无sn
                self.lx_sn = @"0000000000000000";
            }
        }
        compleBlock(error,responseData);
    }];
}

// 写入车身sn
- (void)setCarSNWithSN:(NSString *)sn target:(uint8_t)target successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *data = [IMFunction strToAscll:sn];
    //    [self sendMessageWithChannel:2 property:2 dataParam:data successBlock:success failBlock:fail]; // -- 无权限 ，必须来源为1
    [self sendMessageWithSource:1 target:target channel:CarChannelProductMessage property:ProductMessageChannelCarSN dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

// 获取电池sn 31323334
- (void)getCarBatterySNWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelBatterySN dataParam:nil isRead:YES isRepeat:NO repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            self.batterySN =[IMFunction convertDataToHexStr:responseData];
        }
        compleBlock(error,responseData);
    }];
}

// 写入电池sn
- (void)setCarBatterySNWithSN:(NSString *)sn successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *data = [IMFunction strToAscll:sn];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelBatterySN dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

// 获取电机sn
- (void)getCarMotorSNWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelMotorSN dataParam:nil isRead:YES isRepeat:NO repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            self.motorSN = [IMFunction convertDataToHexStr:responseData];
        }
        compleBlock(error,responseData);
    }];
}

// 写入电机sn
- (void)setCarMotorSNWithSN:(NSString *)sn successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *data = [IMFunction strToAscll:sn];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelMotorSN dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

// 获取电池总容量
- (void)getCarBatterySizeWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelBatteryCapacity dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t batterSize ;
            [responseData getBytes:&batterSize range:NSMakeRange(0, responseData.length)];
            self.batterySize = batterSize/10;
        }
        compleBlock(error,responseData);
    }];
}

// 写入电池总容量
- (void)setCarBatterySizeWithSize:(uint16_t)size successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    uint16_t value = size *10;
    NSData *param = [NSData dataWithBytes:&value length:2];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelBatteryCapacity dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取固件版本号和设备号 <000b0002 0250f821 00>
- (void)getCarFirmwareAndDeviceNumWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelFirmwareAndDeviceNum dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        // 版本号不在此处解析 -- 放到具体车型里解析
        compleBlock(error,responseData);
    }];
}

- (void)getCarHWFirmwareAndDeviceNumWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelHardwareVersion dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        // 版本号不在此处解析 -- 放到具体车型里解析
        compleBlock(error,responseData);
    }];
}

// 获取产品额定电压
- (void)getCarRatedVoltageWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRatedVoltage dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t voltage ;
            [responseData getBytes:&voltage range:NSMakeRange(0, responseData.length)];
            self.ratedVoltage = voltage/10;
        }
        compleBlock(error,responseData);
    }];
}

// 写入额定电压
- (void)setCarRatedVoltageWithPower:(uint16_t)voltage successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    uint16_t value = voltage / 10;
    NSData *param = [NSData dataWithBytes:&value length:2];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRatedVoltage dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取产品额定功率
- (void)getCarRatedPowerWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRatedPower dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t power ;
            [responseData getBytes:&power range:NSMakeRange(0, responseData.length)];
            self.ratedPower = power;
        }
        compleBlock(error,responseData);
    }];
}

// 写入产品额定功率
- (void)setCarRatedPowerWithPower:(uint16_t)power successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *param = [NSData dataWithBytes:&power length:2];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRatedPower dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取设计最高限速
- (void)getCarMaxSpeedWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelMaxSpeed dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t MaxSpeed ;
            [responseData getBytes:&MaxSpeed range:NSMakeRange(0, responseData.length)];
            self.maxSpeed = MaxSpeed/10;
        }
        compleBlock(error,responseData);
    }];
}

// 写入设计最高限速
- (void)setCarMaxSpeedWithSpeed:(uint16_t)speed successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    uint16_t value = speed * 10 ;
    NSData *param = [NSData dataWithBytes:&value length:2];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelMaxSpeed dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取续航里程
- (void)getCarRechargeMileageWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRechargeMileage dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t mileage ;
            [responseData getBytes:&mileage range:NSMakeRange(0, responseData.length)];
            self.rechargeMileage = mileage/10;
        }
        compleBlock(error,responseData);
    }];
}

// 写入续航里程
- (void)setCarRechargeMileageWithMileage:(uint16_t)mile successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    uint16_t value = mile * 10;
    NSData *param = [NSData dataWithBytes:&value length:2];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelRechargeMileage dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取设备唯一ID
- (void)getCarDeviceIDWithTargetDevice:(uint8_t)device compleBlock:(void (^)(NSError *error, NSString *deviceId))compleBlock; {
    [self sendMessageWithSource:2 target:device channel:CarChannelProductMessage property:ProductMessageChannelDeviceID dataParam:nil isRead:YES isRepeat:YES repeatcount:1 compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            compleBlock(error,nil);
        }else {
            NSString *device = [IMFunction dataChangeToString:responseData];
            compleBlock(nil,device);
        }
    }];
}

// 获取产品制造商信息
- (void)getDeviceFactoryMessageWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelFactoryMessage dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            // 生产日期
            NEW_CAR_DATE time ;
            [responseData getBytes:&time range:NSMakeRange(0, 4)];
            NSString *timeStr = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",time.year + 2020,time.month,time.day,time.hour,time.minute,time.second];
            self.factoryDate = timeStr;
            // 生产工厂代号
            uint32_t code ;
            [responseData getBytes:&code range:NSMakeRange(4, 4)];
            self.factoryCode = code;
        }
        compleBlock(error,responseData);
    }];
}
// 写入产品制造商信息
- (void)sendDeviceFactoryMessageWithDate:(NSDate *)date factoryCode:(uint32_t)Factory successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSMutableData *param = [[NSMutableData alloc] init];
    NSArray *nowAry = [KSTimeFormatter returnNowTimeForAryWithdate:date];
    NEW_CAR_DATE time ;
    time.year = [nowAry[0] intValue] - 2020;
    time.month = [nowAry[1] intValue];
    time.day = [nowAry[2] intValue];
    time.hour = [nowAry[3] intValue];
    time.minute = [nowAry[4] intValue];
    time.second = [nowAry[5] intValue];
    NSData *datedata = [NSData dataWithBytes:&time length:4];
    NSData *codedata = [NSData dataWithBytes:&Factory length:4];
    [param appendData:datedata];
    [param appendData:codedata];
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelFactoryMessage dataParam:param repeatcount:0 successBlock:success failBlock:fail];
}

// 获取设备激活状态
- (void)getCarDeviceActivationStatuSsuccessBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    [self sendMessageWithChannel:CarChannelProductMessage property:ProductMessageChannelActivation dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint32_t value ;
            [responseData getBytes:&value range:NSMakeRange(0, 4)];
            if (value == 0) {
                fail(error);
            }else {
                NEW_CAR_DATE time ;
                [responseData getBytes:&time range:NSMakeRange(0, 4)];
//                NSString *timeStr = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",time.year + 2020,time.month,time.day,time.hour,time.minute,time.second];
//                self.activationDate = timeStr;
                NSString *timeStr = [NSString stringWithFormat:@"%d-%d-%d",time.year + 2020,time.month,time.day];
                self.activationDate = timeStr;
                success();
            }
        }else {
            fail(error);
        }
    }];
}

// 车辆激活
- (void)sendCarActivationWith:(NSDate *)date target:(uint8_t)target isE20: (BOOL)isE20 successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSArray *nowAry = [KSTimeFormatter returnNowTimeForAryWithdate:date];
    NEW_CAR_DATE time ;
    time.year = [nowAry[0] intValue] - 2020;
    time.month = [nowAry[1] intValue];
    time.day = [nowAry[2] intValue];
    time.hour = [nowAry[3] intValue];
    time.minute = [nowAry[4] intValue];
    time.second = [nowAry[5] intValue];
    NSData *param = [NSData dataWithBytes:&time length:4];
    uint8_t bytes[] = {0x00};
    NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
    [self sendMessageWithSource:2 target:target channel:CarChannelProductMessage property:ProductMessageChannelActivation dataParam: param repeatcount:0 successBlock:success failBlock:fail];
}

#pragma mark -- 通道三
// 关机重启休眠唤醒发送
- (void)sendCarTurnOffOrOnOrSleepWith:(uint8_t)type compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSData *data = [NSData dataWithBytes:&type length:1];
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelSending dataParam:data isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 关机重启休眠唤醒确认
- (void)confirmCarTurnOffOrOnOrSleepWithCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelCommit dataParam:nil isRead:NO isRepeat:NO repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
    // change mark: 
}

// 恢复出厂设置
- (void)setCarReviewWithGrade:(uint8_t)grade compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSData *data = [NSData dataWithBytes:&grade length:1];
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelReview dataParam:data isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 启动或关闭固件升级
- (void)writeCarUploadOpenOrCloseWithParam:(uint8_t)param successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
   
    // 处理新版协议v11关于此指令数据格式变更的处理。
    NSData *data = nil; //[NSData dataWithBytes:&param length:1];
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelUploadState dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

//读取固件升级状态
- (void)getCarUploadStateCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelUploadState dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 强制固件升级
- (void)setCarNeedUploadWithRank:(int)rank lowest:(NSString *)lowestVersion highest:(NSString *)highrstVersion successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *rankData = [NSData dataWithBytes:&rank length:1];
    NSArray *lowestAry = [lowestVersion componentsSeparatedByString:@"."];
    NSArray *highrstAry = [highrstVersion componentsSeparatedByString:@"."];
    uint32_t lowest = [lowestAry[2] intValue] << 24 | [lowestAry[1] intValue] << 8 | [lowestAry[0] intValue];
    uint32_t heighest = [highrstAry[2] intValue] << 24 | [highrstAry[1] intValue] << 8 |[highrstAry[0] intValue];
    NSData *lowestData = [NSData dataWithBytes:&lowest length:4];
    NSData *highestData = [NSData dataWithBytes:&heighest length:4];
    [paramData appendData:rankData];
    [paramData appendData:lowestData];
    [paramData appendData:highestData];
    
    [self sendMessageWithSource:2 target:0x21 channel:CarChannelCarControll property:CarControllChannelNeedUpload dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            fail(error);
        }else {
            uint8_t resultCode ;
            [responseData getBytes:&resultCode range:NSMakeRange(0, 1)];
            if (resultCode == 0) {
                success();
            }else {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:resultCode]
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:resultCode userInfo:userInfo];
                fail(settingError);
            }
        }
    }];
}

// 获取设备锁定及报警
- (void)getCarLockAlarmCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarControll property:CarControllChannelLockAlarm dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 设置设备锁定及报警 0x21
- (void)setCarLockAlarmWithParam:(uint8_t)param successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {

    NSData *rankData = [NSData dataWithBytes:&param length:1];
    [self sendMessageWithSource:2 target:0x21 channel:CarChannelCarControll property:CarControllChannelLockAlarm dataParam:rankData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            fail(error);
        }else {
            uint8_t resultCode ;
            [responseData getBytes:&resultCode range:NSMakeRange(0, 1)];
            if (resultCode == 0) {
                success();
            }else {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:resultCode]
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:resultCode userInfo:userInfo];
                fail(settingError);
            }
        }
    }];
}

#pragma mark -- 通道四
// 打开文件
- (void)openFileWithType:(uint8_t)openType fileName:(NSString *)fileName compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *typeData = [NSData dataWithBytes:&openType length:1];
    NSData *nameData = [IMFunction strToAscll:fileName];
    uint8_t end = 0x00;
    NSData *endData = [NSData dataWithBytes:&end length:1];
    [paramData appendData:typeData];
    [paramData appendData:nameData];
    [paramData appendData:endData];
    
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelOpen tab:tab dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 写入文件
- (void)writeFileWithHandle:(uint8_t)handle offset:(uint32_t)offset data:(NSData *)data compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *handleData = [NSData dataWithBytes:&handle length:1];
    NSData *offsetData = [NSData dataWithBytes:&offset length:4];
    [paramData appendData:handleData];
    [paramData appendData:offsetData];
    [paramData appendData:data];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelWrite tab:[self currentdateInterval] dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 读取文件
- (void)readFileWithHandle:(uint8_t)handle offset:(uint32_t)offset length:(uint8_t)length compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *handleData = [NSData dataWithBytes:&handle length:1];
    NSData *offsetData = [NSData dataWithBytes:&offset length:4];
    NSData *lengthData = [NSData dataWithBytes:&length length:1];
    [paramData appendData:handleData];
    [paramData appendData:offsetData];
    [paramData appendData:lengthData];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelWrite tab:[self currentdateInterval] dataParam:paramData isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 校验文件 - 读 用于文件下载
- (void)readFileCheckWithHandle:(uint8_t)handle offset:(uint32_t)offset compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *handleData = [NSData dataWithBytes:&handle length:1];
    NSData *offsetData = [NSData dataWithBytes:&offset length:4];
    [paramData appendData:handleData];
    [paramData appendData:offsetData];
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelCheck tab:tab dataParam:paramData isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 校验文件 -写 用于文件上传
- (void)writeFileCheckWithHandle:(uint8_t)handle fileSize:(uint32_t)size offset:(uint32_t)offset checkCrc32:(uint32_t)crc32 compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSData *handleData = [NSData dataWithBytes:&handle length:1];
    NSData *sizeData = [NSData dataWithBytes:&size length:4];
    NSData *offsetData = [NSData dataWithBytes:&offset length:4];
    NSData *crc32Data = [NSData dataWithBytes:&crc32 length:4];
    [data appendData:handleData];
    [data appendData:sizeData];
    [data appendData:offsetData];
    [data appendData:crc32Data];
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelCheck tab:tab dataParam:data isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 关闭文件
- (void)closeFileWithHandle:(uint8_t)handle compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    Byte param[1] = {0x00};
    param[0] = handle;
    NSData *paramData = [NSData dataWithBytes:&param length:1];
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelCloose tab:tab dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 读取文件信息
- (void)readFileMessagaeWithName:(NSString *)fileName compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSData *nameData = [IMFunction strToAscll:fileName];
    [data appendData:nameData];
    uint8_t end = 0x00;
    NSData *endData = [NSData dataWithBytes:&end length:1];
    [data appendData:endData];
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelRead tab:tab dataParam:data isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 删除文件
- (void)deleteFileWithName:(NSString *)fileName successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSData *nameData = [IMFunction strToAscll:fileName];
    [data appendData:nameData];
    uint8_t end = 0x00;
    NSData *endData = [NSData dataWithBytes:&end length:1];
    [data appendData:endData];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelDelegate dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

// 重命名文件
- (void)resetFileNameWithNewName:(NSString *)newName oldName:(NSString *)oldName successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    
    NSMutableData *data = [[NSMutableData alloc] init];
    NSString *fileStr = [NSString stringWithFormat:@"%@>%@",oldName,newName];
    NSData *nameData = [IMFunction strToAscll:fileStr];
    [data appendData:nameData];
    uint8_t end = 0x00;
    NSData *endData = [NSData dataWithBytes:&end length:1];
    [data appendData:endData];
    
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelResetName dataParam:data repeatcount:0 successBlock:success failBlock:fail];
}

// 获取文件列表
- (void)getFileListWithNum:(uint16_t)num fileType:(NSString *)fileType compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSMutableData *paramData = [[NSMutableData alloc] init];
    NSData *offsetData = [NSData dataWithBytes:&num length:2];
    NSData *fileTypeData = [IMFunction strToAscll:fileType];
    Byte end = 0x00;
    NSData *endData = [NSData dataWithBytes:&end length:1];
    [paramData appendData:offsetData];
    [paramData appendData:fileTypeData];
    [paramData appendData:endData];
    uint32_t tab = [self currentdateInterval];
    [self sendMessageWithChannel:CarChannelCarFile property:CarFileChannelGetFileList tab:tab dataParam:paramData isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 解析文件列表 - 返回文件组字典
- (NSDictionary *)analyzeFileListWithData:(NSData *)data {
    if (!data.length) {
        return nil;
    }
    
    NSMutableArray *resultAry = [NSMutableArray arrayWithCapacity:1];
    NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
    NSUInteger indexOffset = 0;
    
    NSUInteger length = data.length;
    Byte *bytes = (Byte *)malloc(length);
    [data getBytes:bytes length:length];
    
    // 1. 错误码
    uint8_t errorCode ;
    [data getBytes:&errorCode range:NSMakeRange(indexOffset++, 1)];
    [resultDic setValue:@(errorCode) forKey:@"errorCode"];
    
    if (errorCode != 0) {
        NSLog(@"文件列表数据错误❌================");
        return nil;
    }
    
    // 2. 请求序号
    uint16_t requestIndex ;
    [data getBytes:&requestIndex range:NSMakeRange(indexOffset, 2)];
    indexOffset += 2;
    [resultDic setValue:@(requestIndex) forKey:@"requestIndex"];
    
    // 3. 目录树剩余节点数
    uint16_t lastFileCount ;
    [data getBytes:&lastFileCount range:NSMakeRange(indexOffset, 2)];
    indexOffset += 2;
    [resultDic setValue:@(lastFileCount) forKey:@"lastFileCount"];
    if (indexOffset >= data.length) {
        return nil;
    }
    do {
        // 4. 文件组1
        // 4.1文件组路径长度 4.2文件组路径名 4.3文件组包含文件数
        uint8_t fileGroupLength ;
        [data getBytes:&fileGroupLength range:NSMakeRange(indexOffset++, 1)];
        
        NSData *fileGroupPathData = [data subdataWithRange:NSMakeRange(indexOffset, fileGroupLength)];
        indexOffset += fileGroupLength;
        NSString *fileGroupPath = [IMFunction convertDataToHexStr:fileGroupPathData];
        uint8_t fileGroupNum ;
        [data getBytes:&fileGroupNum range:NSMakeRange(indexOffset++, 1)];
        
        // 5.文件组内文件列表信息
        // 5.1文件名长度  5.2文件名  5.3文件长度  5.4 修改日期
        NSMutableArray *tempAry = [NSMutableArray arrayWithCapacity:1];
        
        for (int i = 0; i < fileGroupNum; i ++) {
            
            if (indexOffset + 10 > data.length) {
                break;
            }
            uint8_t fileNameLength ;
            [data getBytes:&fileNameLength range:NSMakeRange(indexOffset++, 1)];
            
            NSData *filenameData = [data subdataWithRange:NSMakeRange(indexOffset, fileNameLength)];
            indexOffset += fileNameLength;
            NSString *fileName = [NSString stringWithFormat:@"%@%@",fileGroupPath,[IMFunction convertDataToHexStr:filenameData]];
            
            uint32_t fileSize ;
            [data getBytes:&fileSize range:NSMakeRange(indexOffset, 4)];
            indexOffset += 4;
            
            NEW_CAR_DATE time ;
            [data getBytes:&time range:NSMakeRange(indexOffset, 4)];
            NSString *timeStr = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",time.year + 2020,time.month,time.day,time.hour,time.minute,time.second];
            indexOffset += 4;
            
            IM_FileModel *fileModel = [[IM_FileModel alloc] init];
            NSDictionary *tempDic = @{
                @"nameLength":@(fileNameLength),
                @"name":fileName,
                @"size":@(fileSize),
                @"changeTime":timeStr
            };
            [fileModel setValuesForKeysWithDictionary:tempDic];
            [tempAry addObject:fileModel];
        }
        IM_FileGroupModel *groupModel = [[IM_FileGroupModel alloc] init];
        NSDictionary *groupDic = @{
            @"pathLength":@(fileGroupLength),
            @"path":fileGroupPath,
            @"fileCount":@(fileGroupNum),
            @"fileList":tempAry
        };
        [groupModel setValuesForKeysWithDictionary:groupDic];
        BOOL isHave = NO;
        for (IM_FileGroupModel *group in resultAry) {
            if ([groupModel.path isEqualToString:group.path]) {
                isHave = YES;
                group.fileCount = group.fileCount + groupModel.fileCount;
                NSMutableArray *ishasList = [NSMutableArray arrayWithArray:group.fileList];
                [ishasList addObjectsFromArray:groupModel.fileList];
                group.fileList = (NSArray *)ishasList;
            }
        }
        if (!isHave) {
            [resultAry addObject:groupModel];
        }
    } while (indexOffset < data.length);
    [resultDic setValue:resultAry forKey:@"groupList"];
    return resultDic;
}

#pragma mark -- 通道五
// 存储总容量及剩余容量
- (void)getRAMSizeWithNum:(uint8_t)num compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    Byte param[1] = {0x00};
    param[0] = num;
    NSData *paramData = [NSData dataWithBytes:&param length:2];
    [self sendMessageWithChannel:CarChannelCarMemory property:CarMemoryChannelSize dataParam:paramData isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 擦出m并格式化存储
- (void)deleteRAMWithNum:(uint8_t)num compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    Byte param[2] = {num,0x01};
    NSData *paramData = [NSData dataWithBytes:&param length:2];
    [self sendMessageWithChannel:CarChannelCarMemory property:CarMemoryChannelDelegate dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

#pragma mark -- 通道六
// 读取蓝牙名称
- (void)readBleNameCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingChannelName dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 写入蓝牙名称
- (void)writeBleNameWithName:(NSString *)name successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *nameData = [IMFunction strToAscll:name];
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingChannelName dataParam:nameData repeatcount:0 successBlock:success failBlock:fail];
}

// 读取蓝牙密码
- (void)readBlePasswordCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingChannelPassword dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        if (!error && responseData.length) {
            self.blePassword = [IMFunction convertDataToHexStr:responseData];
            NSLog(@"%@ ==蓝牙密码== %@",responseData,self.blePassword);
        }
        compleBlock(error,responseData);
    }];
}

// 写入蓝牙密码
- (void)writeBlePasswordWithPassword:(NSData *)password successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
        
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingChannelPassword dataParam:password isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        NSLog(@" %@==写入蓝牙密码== %@",error,responseData);
        if (!error && responseData.length) {
            uint8_t result ;
            [responseData getBytes:&result range:NSMakeRange(0, 1)];
            if (result == 0) {
                success();
            }else {
                fail(error);
            }
        }else {
            fail(error);
        }
    }];

}

// 读取蓝牙Mac地址
- (void)readBleMACAddressCompleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingChannelMAC dataParam:nil isRead:YES isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        compleBlock(error,responseData);
    }];
}

// 验证蓝牙密码
- (void)checkBlePasswordWithPassword:(NSData *)password successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    [self sendMessageWithChannel:CarChannelCarBleSetting property:CarBleSettingCheckBlePassword dataParam:password isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        NSLog(@" %@==验证蓝牙密码== %@",error,responseData);
        if (!error && responseData.length) {
            uint8_t result ;
            [responseData getBytes:&result range:NSMakeRange(0, 1)];
            uint8_t check ;
            [responseData getBytes:&check range:NSMakeRange(1, 1)];
            if (result == 0 && check == 1) {
                success();
            }else {
                fail(error);
            }
        }else {
            fail(error);
        }
    }];
}

// 发送消息
- (void)sendMessageWithChannel:(uint8_t)channel property:(uint8_t)property dataParam:(NSData *)param isRead:(BOOL)isRead isRepeat:(BOOL)isRepeat repeatcount:(int)count compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1; // 带有tab
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 1;
    uint8_t source = 0;
    uint8_t length = format.dataType + 1 +param.length;
    
    uint8_t pro = property;
    if (isRead) {
        pro = property & 0x7f;
    }else {
        pro = property | 0x80;
    }
    uint32_t tab = [self currentdateInterval];
    
    IMTCANMessage *message = [IM_NewMessageFactory StandardMessageWithFormat:format key:0 tab:tab length:length source:source target:0 channel:channel property:pro para:param];
    NSLog(@"🌹发送消息🌹: ============%d============ checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- key:%x -- source:%x -- target:%x -- channel:%x -- property:%x -- para:%@  -- newKey:%@",channel,message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.StandardData.source,message.StandardData.target,message.StandardData.channel,message.StandardData.property,message.para,message.key);
    CGFloat time = 1;
    if (channel == 5) {
        time = 2;
    }
    if (channel == 3 && property) {// 恢复出厂设置耗时超时时间延长。
        time = 5;
    }
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:time completion:^(NSError *error, NSData *responseData) {
        if (error) {
            NSDictionary *userInfo = @{
                @"description":[self returnErrorDescriptionWithErrorCode:StandardErrorCodeTimeOut],
                @"errorCode":@(StandardErrorCodeTimeOut)
            };
            NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:StandardErrorCodeTimeOut userInfo:userInfo];
            if (isRepeat) {
                if (count > 2) {
                    compleBlock(settingError,responseData);
                }else {
                    NSLog(@"=================== 44重试🐛🚗标准组 ===============");
                    [self sendMessageWithChannel:channel property:property dataParam:param isRead:isRead isRepeat:isRepeat repeatcount:count compleBlock:compleBlock];
                }
            }else {
                compleBlock(settingError,responseData);
            }
        }else {
            compleBlock(error,responseData);
        }
    }];
}
// 发送消息
- (void)sendMessageWithSource:(uint8_t)source target:(uint8_t)target channel:(uint8_t)channel property:(uint8_t)property dataParam:(NSData *)param isRead:(BOOL)isRead isRepeat:(BOOL)isRepeat repeatcount:(int)count compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1; // 带有tab
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 3;
    uint8_t length = format.dataType + 1 +param.length;
    
    uint8_t pro = property;
    if (isRead) {
        pro = property & 0x7f;
    }else {
        pro = property | 0x80;
    }
    uint32_t tab = [self currentdateInterval];
    
    IMTCANMessage *message = [IM_NewMessageFactory StandardMessageWithFormat:format key:0 tab:tab length:length source:source target:target channel:channel property:pro para:param];
    NSLog(@"🌹发送target消息🌹: ============%d============ checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- key:%x -- source:%x -- target:%x -- channel:%x -- property:%x -- para:%@  -- newKey:%@",channel,message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.StandardData.source,message.StandardData.target,message.StandardData.channel,message.StandardData.property,message.para,message.key);
    CGFloat time = 1;
    if (channel == 5) {
        time = 2;
    }
    if (channel == 3 && property == 3) {// 恢复出厂设置耗时超时时间延长。
        time = 3;
    }
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:time completion:^(NSError *error, NSData *responseData) {
        if (error) {
            NSDictionary *userInfo = @{
                @"description":[self returnErrorDescriptionWithErrorCode:StandardErrorCodeTimeOut],
                @"errorCode":@(StandardErrorCodeTimeOut)
            };
            NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:StandardErrorCodeTimeOut userInfo:userInfo];
            if (isRepeat) {
                if (count > 2) {
                    compleBlock(settingError,responseData);
                }else {
                    NSLog(@"=================== 55重试🐛🚗标准组 ===============");
                    [self sendMessageWithSource:source target:target channel:channel property:property dataParam:param isRead:isRead isRepeat:isRepeat repeatcount:count compleBlock:compleBlock];
                }
            }else {
                compleBlock(settingError,responseData);
            }
        }else {
            compleBlock(error,responseData);
        }
    }];
}


// 发送消息 -- 写入操作 -- 带成功失败回调
- (void)sendMessageWithChannel:(uint8_t)channel property:(uint8_t)property dataParam:(NSData *)param repeatcount:(int)count successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1;
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 1;
    uint32_t tab = [self currentdateInterval];
    uint8_t pro = property | 0x80;
    
    IMTCANMessage *message = [IM_NewMessageFactory StandardMessageWithFormat:format key:0 tab:tab length:2+param.length source:0 target:0 channel:channel property:pro para:param];
    NSLog(@"🌹发送消息🌹: ======================== checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- key:%x -- source:%x -- target:%x -- channel:%x -- property:%x -- para:%@  -- newKey:%@",message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.StandardData.source,message.StandardData.target,message.StandardData.channel,message.StandardData.property,message.para,message.key);
    NSInteger time = 1.0;
    if (channel == CarChannelCarMemory) {
        time = 3.0;
    }
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:time completion:^(NSError *error, NSData *responseData) {
        if (error) {
            if (count > 2) {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:StandardErrorCodeTimeOut],
                    @"errorCode":@(StandardErrorCodeTimeOut)
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:StandardErrorCodeTimeOut userInfo:userInfo];
                fail(settingError);
            }else {
                NSLog(@"=================== 11重试🐛🚗标准组 ===============");
                [self sendMessageWithChannel:channel property:property dataParam:param repeatcount:count successBlock:success failBlock:fail];
            }
        }else {
            uint8_t resultCode ;
            [responseData getBytes:&resultCode range:NSMakeRange(0, responseData.length)];
            if (resultCode == 0) {
                success();
            }else {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:resultCode],
                    @"errorCode":@(resultCode)
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:resultCode userInfo:userInfo];
                fail(settingError);
            }
        }
    }];
}

// 发送消息 - 带tab
- (void)sendMessageWithChannel:(uint8_t)channel property:(uint8_t)property tab:(uint32_t)tab dataParam:(NSData *)param isRead:(BOOL)isRead isRepeat:(BOOL)isRepeat repeatcount:(int)count compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1;
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 1;
    uint8_t pro = property;
    if (isRead) {
        pro = property & 0x7f;
    }else {
        pro = property | 0x80;
    }
    IMTCANMessage *message = [IM_NewMessageFactory StandardMessageWithFormat:format key:0 tab:tab length:2+param.length source:0 target:0 channel:channel property:pro para:param];
    NSLog(@"🌹发送消息🌹: ======================== checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- Key:%hhu -- source:%x -- target:%x -- channel:%x -- property:%x -- para:%@  -- newKey:%@",message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.StandardData.source,message.StandardData.target,message.StandardData.channel,message.StandardData.property,message.para,message.key);
    
    CGFloat time = channel == CarChannelCarFile ? 3 : 1;
    if (channel == CarChannelCarFile && property == CarFileChannelWrite) {
        time = 1.0;
    }
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:time completion:^(NSError *error, NSData *responseData) {
        if (error) {
            NSDictionary *userInfo = @{
                @"description":[self returnErrorDescriptionWithErrorCode:StandardErrorCodeTimeOut],
                @"errorCode":@(StandardErrorCodeTimeOut)
            };
            NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:StandardErrorCodeTimeOut userInfo:userInfo];
            
            if (isRepeat) {
                if (count > 2) {
                    compleBlock(settingError,responseData);
                }else {
                    NSLog(@"=================== 22重试🐛🚗标准组 ===============");
                    [self sendMessageWithChannel:channel property:property tab:tab+1 dataParam:param isRead:isRead isRepeat:isRepeat repeatcount:count compleBlock:compleBlock];
                }
            }else {
                compleBlock(settingError,responseData);
            }
        }else {
            compleBlock(error,responseData);
        }
    }];
}

// 发送消息 - 带设备
- (void)sendMessageWithSource:(uint8_t)source target:(uint8_t)target channel:(uint8_t)channel property:(uint8_t)property dataParam:(NSData *)param repeatcount:(int)count successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1;
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 3;
    uint32_t tab = [self currentdateInterval];
    uint8_t pro = property | 0x80;
    
    IMTCANMessage *message = [IM_NewMessageFactory StandardMessageWithFormat:format key:0 tab:tab length:4+param.length source:source target:target channel:channel property:pro para:param];
    NSLog(@"🌹发送消息🌹: ======================== checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- key:%x -- source:%x -- target:%x -- channel:%x -- property:%x -- para:%@  -- newKey:%@",message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.StandardData.source,message.StandardData.target,message.StandardData.channel,message.StandardData.property,message.para,message.key);
    
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:1.0 completion:^(NSError *error, NSData *responseData) {
        if (error) {
            if (count > 3) {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:StandardErrorCodeTimeOut],
                    @"errorCode":@(StandardErrorCodeTimeOut)
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:StandardErrorCodeTimeOut userInfo:userInfo];
                fail(settingError);
            }else {
                NSLog(@"=================== 33重试🐛🚗标准组 ===============");
                [self sendMessageWithSource:source target:target channel:channel property:property dataParam:param repeatcount:count successBlock:success failBlock:fail];
            }
        }else {
            uint8_t resultCode ;
            [responseData getBytes:&resultCode range:NSMakeRange(0, responseData.length)];
            if (resultCode == 0) {
                success();
            }else {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:resultCode],
                    @"errorCode":@(resultCode)
                };
                NSError *settingError = [NSError errorWithDomain:StandardErrorCodeDomain code:resultCode userInfo:userInfo];
                fail(settingError);
            }
        }
    }];
}

// 返回标准错误信息说明
- (NSString *)returnErrorDescriptionWithErrorCode:(StandardErrorCode)errorCode {
    NSString *errorDescription = @"";
    if (errorCode == StandardErrorCodeSuccess) {
        errorDescription = @"操作正确";
    }else if (errorCode == StandardErrorCodeParamError) {
        errorDescription = @"参数错误";
    }else if (errorCode == StandardErrorCodeNotSupport) {
        errorDescription = @"目标设备不支持此操作";
    }else if (errorCode == StandardErrorCodeNotAllowed) {
        errorDescription = @"当前状态不允许进行此操作";
    }else if (errorCode == StandardErrorCodeNotOperation) {
        errorDescription = @"无操作权限";
    }else if (errorCode == StandardErrorCodeExecutionError) {
        errorDescription = @"内部执行错误";
    }else if (errorCode == StandardErrorCodeTimeOut) {
        errorDescription = @"消息超时";
    }else if (errorCode == StandardErrorCodeRepeatFail) {
        errorDescription = @"重试错误";
    }
    return errorDescription;
}

// 返回当前时间戳的后四位
-(uint32_t)currentdateInterval {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    timeSp = [timeSp substringWithRange:NSMakeRange(timeSp.length - 4, 4)];
    return (uint32_t)[timeSp intValue];
}

// CRC32校验 -- 结果
- (uint32_t)crc32CheckWithData:(NSData *)data {
    NSUInteger length = data.length;
    Byte *bytes = (Byte *) malloc(length);
    [data getBytes:bytes length:length];
    uint32_t crc32 = 0xFFFFFFFF; // 初值 0xFFFFFFFF
    while (length--) {
        crc32 = (crc32 >> 8) ^ CRC32_TABLE [(crc32 ^ *bytes++) & 0xFF];
    }
    return crc32 ^ 0xffffffff;
}

#pragma mark - Statistics
- (void)addValue:(double)value toArray:(NSMutableArray *)array limited:(BOOL)limited {
    if (limited && array.count >= 100) {
        [array removeObjectAtIndex:0];
    }
    [array addObject:@(value)];
}

- (NSMutableArray *)powers {
    if (!_powers) {
        _powers = @[].mutableCopy;
    }
    return _powers;
}

- (NSMutableArray *)speeds {
    if (!_speeds) {
        _speeds = @[].mutableCopy;
    }
    return _speeds;
}

- (NSMutableArray *)temperatures {
    if (!_temperatures) {
        _temperatures = @[].mutableCopy;
    }
    return _temperatures;
}

- (NSMutableArray *)tripEnergies {
    if (!_tripEnergies) {
        _tripEnergies = @[].mutableCopy;
    }
    return _tripEnergies;
}

// 返回文件操作的错误提示语
- (NSString *)returnFileErrorStringWithCode:(int8_t)errorCode {
    NSString *errorStr = @"";
    switch (errorCode) {
        case StandardFileErrorCodeSuccess:
            errorStr = @"操作成功";
            break;
        case StandardFileErrorCodeNotFile:
            errorStr = @"文件不存在";
            break;
        case StandardFileErrorCodeNotSupport:
            errorStr = @"不支持的操作";
            break;
        case StandardFileErrorCodeConflict:
            errorStr = @"操作冲突";
            break;
        case StandardFileErrorCodeOutUpperLimit:
            errorStr = @"同时打开的文件数量已达上限";
            break;
        case StandardFileErrorCodeHandleError:
            errorStr = @"非法句柄";
            break;
        case StandardFileErrorCodeSystemError:
            errorStr = @"文件系统错误";
            break;
        case StandardFileErrorCodeFileBottomError:
            errorStr = @"文件底层 IO 错误";
            break;
        case StandardFileErrorCodeParamError:
            errorStr = @"输入参数错误";
            break;
        case StandardFileErrorCodeInternalProgramError:
            errorStr = @"系统内部程序错误";
            break;
        case StandardFileErrorCodeNotAllowed:
            errorStr = @"当前状态不允许相应操作";
            break;
        case StandardFileErrorCodeNotOperation:
            errorStr = @"无操作权限";
            break;
        case StandardFileErrorCodeErrorOther:
            errorStr = @"其他错误";
            break;
        case StandardFileErrorCodeTimeOut:
            errorStr = @"超时错误";
            break;
        case StandardFileErrorCodeRepeatFail:
            errorStr = @"重试错误";
            break;
        default:
            break;
    }
    return errorStr;
}

@end
